package map.android.baidu.carpool.page.usercenter;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.AsyncHttpClient;
import com.baidu.lbs.net.http.AsyncHttpResponseHandler;
import com.baidu.lbs.net.http.RequestParams;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import com.baidu.lbs.place.user.UserCenter;
import com.baidu.mapframework.api.ComAPIManager;
import com.baidu.mapframework.component.comcore.exception.ComException;
import com.baidu.mapframework.widget.MProgressDialog;
import com.baidu.mapframework.widget.MToast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import map.android.baidu.carpool.Config;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.WebConfig;
import map.android.baidu.carpool.data.impl.ModifierUserInfoData;
import map.android.baidu.carpool.data.impl.UserCenterData;
import map.android.baidu.carpool.model.URLModel;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.response.ModifierUserInfoResponse;
import map.android.baidu.carpool.response.UserCenterResponse;
import map.android.baidu.carpool.setting.UserInfoSetting;
import map.android.baidu.carpool.utils.InstructionsForUserDialog;
import map.android.baidu.carpool.utils.StatisticsUtil;
import map.android.baidu.carpool.utils.TitleHelpler;
import map.android.baidu.carpool.utils.UploadPicUtil;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by zhangtongyu on 15/4/3.
 * 个人中心的我的资料页面
 */
public class UserInfoPage extends CarpoolBasePage implements View.OnClickListener {
    private Context mContext;
    private LayoutInflater mInflater;
    private Resources mRes;

    /* 用来标识请求照相功能的activity */
    private static final int CAMERA_WITH_DATA = 3023;

    /* 用来标识请求gallery的activity */
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    private static final int PHOTO_CROP = 3033;


    private View mView;
    private TitleHelpler mTitleHelper;

    private ImageView mHeadPicIm;
    private TextView mContactNumTv;
    private TextView mNickNameTv;
    private TextView mSexTv;
    private LinearLayout mChezhujiamengLin;
    private Button mChezhujiamengBt;

    private ImageLoader mImageLoader;
    private DisplayImageOptions options;


    private Bundle mBundle;
    private ModifierUserInfoResponse modifierUserInfoResponse;
    private IDataStatusChangedListener<ModifierUserInfoResponse> modifierUserInfoListener = new IDataStatusChangedListener<ModifierUserInfoResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<ModifierUserInfoResponse> data, ModifierUserInfoResponse response, int dataStatus) {
            if (dataStatus == ComNetData.DATA_STATUS_SUCCESS) {
                if (response != null && response.data != null) {
                    MToast.show(mContext, "修改成功");
                } else {
                    MToast.show(mContext, "网络连接异常，请检查网络");
                }
            } else {
                MToast.show(mContext, "网络连接异常，请检查网络");
            }

        }
    };

    private IDataStatusChangedListener<UserCenterResponse> userCenterResponseListener = new IDataStatusChangedListener<UserCenterResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<UserCenterResponse> data, UserCenterResponse response, int dataStatus) {
            if (dataStatus == ComNetData.DATA_STATUS_SUCCESS) {
                if (response != null && response.data != null) {
                    updateUI(response);
                } else {
                    MToast.show(mContext, "网络连接异常，请检查网络");
                }
            } else {
                MToast.show(mContext, "网络连接异常，请检查网络");
            }
        }
    };

    private void updateUI(UserCenterResponse response) {
        if(response.data.userInfo != null) {
            if (TextUtils.isEmpty(response.data.userInfo.mobile)) {
                mContactNumTv.setText("绑定手机号");
            } else {
                mContactNumTv.setText(response.data.userInfo.mobile);
            }
            if ("1".equals(response.data.userInfo.gender)) {
                mSexTv.setText("男");
                mNickNameTv.setText(response.data.userInfo.nickname + "先生");
            } else {
                mSexTv.setText("女");
                mNickNameTv.setText(response.data.userInfo.nickname + "女士");
            }
            if (!TextUtils.isEmpty(response.data.userInfo.userPic)) {
                displayImageView(response.data.userInfo.userPic, mHeadPicIm);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = APIProxy.res().getBaseActivity();
        mInflater = APIProxy.res().getInflater();
        mRes = APIProxy.res().getResources();
        if (mView == null) {
            mBundle = getArguments();
            mView = APIProxy.res().inflate(R.layout.layout_page_user_info, container, false);
            initImageLoader();
            initView();
            ComAPIManager.getComAPIManager().
                    getResourceAPI(getComId()).getBaseActivity().getWindow().
                    setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            fillView();
        } else {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
        }
        requestUsercenterData();
        return mView;
    }

    private void requestUsercenterData() {
        UserCenterData userCenterData = new UserCenterData(mContext);
        userCenterData.post(userCenterResponseListener);
    }

    private void fillView() {
        if (mBundle == null) {
            return;
        }
        UserCenterResponse.UserInfoSimple userInfoSimple = null;
        if (mBundle.containsKey(UserCenterResponse.UserInfoSimple.class.getName())) {
            userInfoSimple = (UserCenterResponse.UserInfoSimple) mBundle.getSerializable(UserCenterResponse.UserInfoSimple.class.getName());
        }
        if (userInfoSimple != null) {
            if (TextUtils.isEmpty(userInfoSimple.mobile)) {
                mContactNumTv.setText("绑定手机号");
            } else {
                mContactNumTv.setText(userInfoSimple.mobile);
            }
            if ("1".equals(userInfoSimple.gender)) {
                mSexTv.setText("男");
                mNickNameTv.setText(userInfoSimple.nickname + "先生");
            } else {
                mSexTv.setText("女");
                mNickNameTv.setText(userInfoSimple.nickname+ "女士");
            }
            if(!TextUtils.isEmpty(userInfoSimple.userPic)){
                displayImageView(userInfoSimple.userPic, mHeadPicIm);
            }

        }
    }

    private void initView() {
        initTitleBar();
        mHeadPicIm = (ImageView) mView.findViewById(R.id.im_user_info_head);
        mContactNumTv = (TextView) mView.findViewById(R.id.tv_user_info_phone_num);
        mNickNameTv = (TextView) mView.findViewById(R.id.tv_user_nickname);
        mSexTv = (TextView) mView.findViewById(R.id.tv_user_sex);
        mChezhujiamengLin = (LinearLayout) mView.findViewById(R.id.lin_chezhujiameng_container);
        mChezhujiamengBt = (Button) mView.findViewById(R.id.bt_chezhujiameng);

        mHeadPicIm.setOnClickListener(this);
        mContactNumTv.setOnClickListener(this);
        mNickNameTv.setOnClickListener(this);
        mSexTv.setOnClickListener(this);
        mChezhujiamengBt.setOnClickListener(this);
    }

    private void initTitleBar() {
        mTitleHelper = new TitleHelpler(mView);
        mTitleHelper.setLeftView(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBundle.putBoolean("needRefresh", true);
                goBack(mBundle);
            }
        });
        mTitleHelper.setCenterView("个人资料");
    }

    private void showPickPicDialog() {

        new UploadPicUtil().showCommentDialog(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                switch (position) {
                    case 0:
                        // 点击拍照
                        // 加入页面去向意图，判断是拍照还是从相册选择
                        MToast.show(mContext, "点击拍照");
                        if (UploadPicUtil.uploadListDialog != null) {
                            UploadPicUtil.uploadListDialog.dismiss();
                        }
                        takeAphotoWithCamera();
                        break;
                    case 1:
                        // 从相册上传
                        // 加入页面去向意图，判断是拍照还是从相册选择
                        MToast.show(mContext, "从相册上传");
                        if (UploadPicUtil.uploadListDialog != null) {
                            UploadPicUtil.uploadListDialog.dismiss();
                        }
                        choosePhotoWithAlbum();
                        break;
                    case 2:
                        // 点击取消
                        if (UploadPicUtil.uploadListDialog != null) {
                            UploadPicUtil.uploadListDialog.dismiss();
                        }
                        break;
                }
            }
        }, mContext);
    }

    private Uri photoUri = null;
    private File dir;

    private void takeAphotoWithCamera() {
        if (UploadPicUtil.uploadListDialog != null) {
            UploadPicUtil.uploadListDialog.dismiss();
        }

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyy_MM_dd_HH_mm_ss");
            try {
                dir = new File(APIProxy.settings().getComStoragePath(getComId()) + "/BaiduMap/coms/carpool");
                if (!dir.exists()) {
                    dir.mkdirs();
                }
            } catch (ComException e) {
                e.printStackTrace();
            }
            File picFile = new File(dir, timeStampFormat.format(new Date()) + ".png");
            if (picFile == null) {
                MToast.show(mContext, "请确认已插入SD卡以备照片储存");
                return;
            }
            photoUri = Uri.fromFile(picFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            APIProxy.res().getBaseActivity()
                    .startActivityForResult(intent, CAMERA_WITH_DATA);
        } else {
            MToast.show(mContext, "请确认已插入SD卡以备照片储存");
        }
    }

    private void choosePhotoWithAlbum() {
        if (UploadPicUtil.uploadListDialog != null) {
            UploadPicUtil.uploadListDialog.dismiss();
        }
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        /*
         * intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1);
		 * intent.putExtra("outputX", 80); intent.putExtra("outputY", 80);
		 */
        intent.putExtra("return-data", true);
        APIProxy.res().getBaseActivity()
                .startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.im_user_info_head:
                // 更换头像
                if(Config.MONKEY_OPEN){
                    return;
                }
                showPickPicDialog();
                break;
            case R.id.tv_user_info_phone_num:
                // 绑定手机号
                if(Config.MONKEY_OPEN){
                    return;
                }
                UserCenter.bindPhone();
                break;
            case R.id.tv_user_nickname:
                // 填写资料
                showFillUserInfo();
                break;
            case R.id.tv_user_sex:
                // 填写资料
                showFillUserInfo();
                break;
            case R.id.bt_chezhujiameng:
                // 车主加盟
                if(Config.MONKEY_OPEN){
                    return;
                }
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_JOIN_DRIVER_TEAM, "");
                UserInfoSetting.goToWebShell(URLModel.CARE_JOIN_URL);
                break;
        }
    }

    private void showFillUserInfo() {
        int sexInt = 1;
        if(mSexTv != null){
            if("男".equals(mSexTv.getText())){
            } else {
                sexInt = 2;
            }
        }
        InstructionsForUserDialog dialog = new InstructionsForUserDialog(getActivity(), new InstructionsForUserDialog.CallBack() {
            @Override
            public void inputMessageComplete(InstructionsForUserDialog.UserinputInfo userinputInfo) {
                ModifierUserInfoData modifierUserInfoData = new ModifierUserInfoData(mContext);
                if (userinputInfo.sex == 1) {
                    mSexTv.setText("男");
                    mNickNameTv.setText(userinputInfo.name + "先生");
                    modifierUserInfoData.setNewGender("1");
                } else {
                    mSexTv.setText("女");
                    mNickNameTv.setText(userinputInfo.name + "女士");
                    modifierUserInfoData.setNewGender("2");
                }
                modifierUserInfoData.setNewNickname(userinputInfo.name);
                modifierUserInfoData.post(modifierUserInfoListener);
            }
        }, sexInt);
        dialog.show();
    }

    Bitmap mPhotoBitmap = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_PICKED_WITH_DATA && null != data) {
            if (!data.hasExtra("data")) {
                Uri uri = data.getData();
                startPhotoZoom(uri);
            } else if (data.hasExtra("data")) {
                if (mPhotoBitmap != null)//如果不释放的话，不断取图片，将会内存不够
                    mPhotoBitmap.recycle();
                    mPhotoBitmap = (Bitmap) data.getExtras().get("data");
                    MToast.show(mContext, "获取照片失败");
            }
        }  else if (requestCode == CAMERA_WITH_DATA) {
            Uri uri = photoUri;
            startPhotoZoom(uri);
        } else if (requestCode == PHOTO_CROP){
            if(data != null && data.getExtras() != null){
                mPhotoBitmap = data.getExtras().getParcelable("data");
                sendPicFile();
            }
        } else{
            MToast.show(mContext, "获取照片失败");
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CROP);
    }

    private Bitmap decodeBitMap(String path) {
        BitmapFactory.Options op = new BitmapFactory.Options();
        op.inSampleSize = 4;
        op.inTempStorage = new byte[100 * 1024];
        op.inPreferredConfig = Bitmap.Config.RGB_565;
        op.inPurgeable = true;
        op.inInputShareable = true;
        if (mPhotoBitmap != null)//如果不释放的话，不断取图片，将会内存不够
            mPhotoBitmap.recycle();
        mPhotoBitmap = BitmapFactory.decodeFile(path, op);
        return mPhotoBitmap;
    }


    private void sendPicFile() {
        File uploadPic = null;
        File uploadPicDir = null;
        try {
            uploadPicDir = new File(APIProxy.settings().getComStoragePath(
                    this.getComId()));
            if (!uploadPicDir.exists())
                uploadPicDir.mkdirs();
            uploadPic = new File(APIProxy.settings().getComStoragePath(
                    this.getComId())
                    + "/"
                    + Calendar.getInstance().getTimeInMillis()
                    + (int) Math.floor(Math.random() * 1000));
        } catch (ComException e) {
            e.printStackTrace();
        }
        if (mPhotoBitmap == null) {
            MToast.show(mContext, "您未选择照片或照片无效");
            MProgressDialog.dismiss();
            return;
        }
        UploadPicUtil.compressBmpToFile(mPhotoBitmap, uploadPic);


        AsyncHttpClient mAsyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        try {
            params.put("picFile", uploadPic);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        params.put("bduss", UserInfoSetting.getBduss());
        mAsyncHttpClient.post(WebConfig.getUrl(WebConfig.URL_ID_MODIFIER_HEAD_PIC), params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(content);
                    int errNo = jsonObject.optInt("errNo");
                    String errMsg = jsonObject.optString("errMsg");
                    JSONObject data = jsonObject.optJSONObject("data");
                    if (data != null && errNo == 0) {
                        String picUrl = data.optString("picUrl");
                        if (!TextUtils.isEmpty(picUrl)) {
                            displayImageView(picUrl, mHeadPicIm);
                            MToast.show(mContext, "上传头像成功");
                        }
                    } else {
                        MToast.show(mContext, "上传头像失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable error, String content) {
                MToast.show(APIProxy.res().getBaseActivity(), "上传头像失败");
            }
        });
    }

    private void initImageLoader() {
        mImageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .cacheInMemory()
                .cacheOnDisc()
                .showImageForEmptyUri(APIProxy.res().getDrawable(R.drawable.gray_tangle))
                .cacheInMemory().build();
    }

    private void displayImageView(String url, ImageView imageView) {
        //  String imgUrlString = url;
        String finalUrl = "";
        finalUrl = url;
        mImageLoader.clearDiskCache();
        mImageLoader.clearMemoryCache();
        mImageLoader.displayImage(finalUrl, imageView, options, new SimpleImageLoadingListener());

    }

    @Override
    public boolean onBackPressed() {
        mBundle.putBoolean("needRefresh", true);
        goBack(mBundle);
        return true;
    }
}
